<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="final，多态">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日拱一卒-day8">
<meta property="og:url" content="http://yoursite.com/2020/04/20/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day8/index.html">
<meta property="og:site_name" content="很惭愧，就做了一点微小的工作">
<meta property="og:description" content="final，多态">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-20T12:11:07.000Z">
<meta property="article:modified_time" content="2020-05-17T18:12:07.564Z">
<meta property="article:author" content="文予">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2020/04/20/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java日拱一卒-day8 | 很惭愧，就做了一点微小的工作</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">很惭愧，就做了一点微小的工作</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">念念不忘，必有回响</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/04/20/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/wenyu.png">
      <meta itemprop="name" content="文予">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="很惭愧，就做了一点微小的工作">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java日拱一卒-day8
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-20 20:11:07" itemprop="dateCreated datePublished" datetime="2020-04-20T20:11:07+08:00">2020-04-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-18 02:12:07" itemprop="dateModified" datetime="2020-05-18T02:12:07+08:00">2020-05-18</time>
              </span>

          
            <div class="post-description">final，多态</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="final修饰符"><a href="#final修饰符" class="headerlink" title="final修饰符"></a><code>final</code>修饰符</h2><p><code>final</code>关键字可用于修饰类、变量和方法，用于表示它修饰的类、方法和变量不可改变。用于<code>final</code>变量火地初始值之后不能被重新赋值，因此<code>final</code>修饰成员变量和修饰局部变量的时候有一定的不同。</p>
<h3 id="final成员变量"><a href="#final成员变量" class="headerlink" title="final成员变量"></a><code>final</code>成员变量</h3><p>对于final修饰的成员变量而言，一旦有了初始值，就不能被重新赋值，如果既没有在定义成员变量时指定初始值，也没有在初始化块、构造器中为成员变量指定初始值，那么这些成员变量的值将一直是系统默认分配的<code>0</code>、<code>&#39;\u0000&#39;</code>、<code>false</code>或<code>null</code>，因此Java语法规定：final修饰的成员变量必须由程序员显式指定初始值。<br>归纳起来，<code>final</code>修饰的类变量、实例变量能指定初始值的地方如下</p>
<ul>
<li>类变量：必须在静态初始化块中指定初始值或声明该类变量时指定初始值，而且只能在两个地方其中之一指定。</li>
<li>实例变量：必须在非静态初始化块、声明该实例变量或构造器中指定初始值，而且只能在三个地方其中之一指定。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalVariableTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 定义成员变量的时候指定默认值</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> a = <span class="number">6</span>;</span><br><span class="line">    <span class="comment">// 以下变量将在构造器或初始化快中分配初始值</span></span><br><span class="line">    <span class="keyword">final</span> String str;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> c;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">static</span> <span class="keyword">double</span> d;</span><br><span class="line">    <span class="comment">// 既没有指定默认值，又没有在初始化块、构造器中指定初始值</span></span><br><span class="line">    <span class="comment">// 下面定义的ch实例变量是不合法的</span></span><br><span class="line">    <span class="comment">// final char ch;</span></span><br><span class="line">    <span class="comment">// 初始化块</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// 在初始化块中为实例变量指定初始值，合法</span></span><br><span class="line">        str = <span class="string">"hello"</span>;</span><br><span class="line">        <span class="comment">// 定义a实例变量时已经指定了默认值，不能重新赋值，因此下面语句非法</span></span><br><span class="line">        <span class="comment">// a = 9;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 静态初始化块，可对没有指定默认值的类变量指定初始值</span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="comment">// 在静态初始化块中为类变量指定初始值，合法</span></span><br><span class="line">        d = <span class="number">5.6</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 构造方法，可对既没有指定默认值，有没有在初始化块中指定指定初始值的实例变量指定初始值</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">FinalVariableTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 如果初始化块中已经对str指定初始值，那么在构造器中就不能对final变量重新赋值，以下语句非法</span></span><br><span class="line">        <span class="comment">// str = "java";</span></span><br><span class="line">        c = <span class="number">5</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">changeFinal</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 普通方法不能为final修饰的成员变量赋值</span></span><br><span class="line">        <span class="comment">// d = 1.2;</span></span><br><span class="line">        <span class="comment">// 不能在普通方法中为final成员变量指定初始值</span></span><br><span class="line">        <span class="comment">// ch = 'a';</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        FinalVariableTest ft = <span class="keyword">new</span> FinalVariableTest();</span><br><span class="line">        System.out.println(ft.a);</span><br><span class="line">        System.out.println(ft.c);</span><br><span class="line">        System.out.println(ft.d);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="final局部变量"><a href="#final局部变量" class="headerlink" title="final局部变量"></a><code>final</code>局部变量</h3><p>系统不会对局部变量进行初始化，局部变量必须又程序员显式初始化。因此使用<code>final</code>修饰局部变量时，既可以在定义时指定默认值，也可以不指定默认值<br>如果<code>final</code>修饰的局部变量在定义时没有指定默认值，则可以在后面代码中对该变量赋值，但只能一次，不能重复赋值；如果<code>final</code>叙事的局部变量在定义时已经指定默认值，则后面代码中不能再对该变量赋值。</p>
<h3 id="final方法"><a href="#final方法" class="headerlink" title="final方法"></a><code>final</code>方法</h3><p><code>final</code>修饰的方法不可被重写，如果出于某些原因，不希望字类重写父类的某个方法，则可以使用<code>final</code>修饰该方法。例如<code>Object</code>类中有一个<code>final</code>方法：<code>getClass()</code>，因为Java不希望任何类重写这个方法，所有使用<code>final</code>修饰这个方法，但对于该类提供的<code>toString()</code>、<code>equals()</code>方法，都允许子类重写<br>以下程序试图重写<code>final</code>方法，将会引发编译错误</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalMethodTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sub</span> <span class="keyword">extends</span> <span class="title">FinalMethodTest</span></span>&#123;</span><br><span class="line">    <span class="comment">//下面定义的方法将会出现编译错误，不能重写final方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于一个<code>private</code>方法，因为它仅在当前类中可见，其子类无法访问该方法，所以子类无法重写该方法。但是字类可以定义一个具有相同方法名、相同形参列表、相同返回值类型的方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrivateFinalMethodTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sub</span> <span class="keyword">extends</span> <span class="title">PrivateFinalMethodTest</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="final类"><a href="#final类" class="headerlink" title="final类"></a><code>final</code>类</h3><p><code>final</code>修饰的类不可以有子类，例如<code>java.lang.Math</code>类就是一个final类，不可以有子类。<br>当子类继承父类的时候，将可以访问到父类内部数据，并可以通过重写父类方法的方式来改变父类方法的实现细节，这可能导致一些不安全因素。为了保证某个类不可被继承，则可以使用<code>final</code>修饰这个类。</p>
<h2 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h2><h3 id="多态性"><a href="#多态性" class="headerlink" title="多态性"></a>多态性</h3><p>Java引用变量有两个类型：编译时类型，运行时类型。编译时类型由声明该变量使用的类型决定，运行时类型由实际赋给该变量的值决定。如果编译时类型和运行时类型不一致，就可能出现多态。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseClass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> book = <span class="number">6</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">base</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"父类的普通方法"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"父类的被覆盖的方法"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SubClass</span> <span class="keyword">extends</span> <span class="title">BaseClass</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 重新定义一个book实例变量隐藏父类的book实例变量</span></span><br><span class="line">    <span class="keyword">public</span> String book = <span class="string">"隐藏上面的int book = 6"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"子类的覆盖父类的方法"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sub</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"子类的普通方法"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 下面编译时类型与运行时类型一致，不存在多态</span></span><br><span class="line">        BaseClass bc = <span class="keyword">new</span> BaseClass();</span><br><span class="line">        <span class="comment">// 输出6</span></span><br><span class="line"></span><br><span class="line">        System.out.println(bc.book);</span><br><span class="line">        <span class="comment">// 下面两次调用将执行BaseClass的方法</span></span><br><span class="line">        bc.base();</span><br><span class="line">        bc.test();</span><br><span class="line">        <span class="comment">// 下面编译时类型和运行时类型一致，不存在多态</span></span><br><span class="line">        SubClass sc = <span class="keyword">new</span> SubClass();</span><br><span class="line">        <span class="comment">// 输出"隐藏xxxx"</span></span><br><span class="line">        System.out.println(sc.book);</span><br><span class="line">        <span class="comment">// 下面调用将执行从父类继承到的base()方法</span></span><br><span class="line">        sc.base();</span><br><span class="line">        <span class="comment">// 下面调用将执行当前类的test()方法</span></span><br><span class="line">        sc.test();</span><br><span class="line">        <span class="comment">// 下面编译时类型与运行时类型不一致，多态发生</span></span><br><span class="line">        BaseClass ploymophicBC = <span class="keyword">new</span> SubClass();</span><br><span class="line">        <span class="comment">// 输出6，说明访问的是父类对象的实例变量</span></span><br><span class="line">        System.out.println(ploymophicBC.book);</span><br><span class="line">        <span class="comment">// 下面调用从父类继承到的base()方法</span></span><br><span class="line">        ploymophicBC.base();</span><br><span class="line">        <span class="comment">// 当前类的test()方法</span></span><br><span class="line">        ploymophicBC.test();</span><br><span class="line">        <span class="comment">// 因为ploymophicBC的编译时类型是BaseClass，而BaseClass类没有sub()方法，所以下面代码会报错</span></span><br><span class="line">        <span class="comment">// ploymophicBC.sub();</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面程序的<code>main()</code>方法中显式创建了三个引用变量，对于前两个引用变量<code>be</code>和<code>sc</code>，它们的编译时类型和运行时类型完全相同，因此调用他们的成员变量和方法完全正常。但是<code>ploymophicBC</code>比较特殊，编译时类型为<code>BaseClass</code>，而运行时类型为<code>SubClass</code>，当调用该引用变量的<code>test()</code>方法（<code>BaseClass</code>中定义了该方法，子类<code>SubClass</code>覆盖了父类的该方法）时，实际执行的是<code>SubClass</code>类中覆盖后的<code>test()</code>方法，这就可能出现多态了。<br>因为子类实际上是一种特殊的父类，因此Java允许把一个子类对象直接赋值给一个父类引用变量，无须任何类型变换，或者称为向上转型，向上转型由系统自动完成（有点像自动类型转换）。<br>当把一个子类对象直接赋值类父类引用对象时，例如<code>BaseClass ploymophicBC = new SubClass();</code>，这个<code>ploymophicBC</code>引用变量的编译时类型是<code>BaseClass</code>，而运行时类型是<code>SubClass</code>，当运行时调用该引用变量的方法时，该方法行为总是表现出子类的方法特征，而不是父类的方法特征，这就可能导致相同类型的变量，调用同一个方法时呈现出多种不同的行为特征，这就是多态。<br>引用变量在编译阶段只能调用它编译时类型所具有的方法，但运行时则执行它运行时类型所具有的方法。因此，编写代码的时候，引用变量只能调用声明该变量时所用类里包含的方法。例如，通过<code>Object p = new Person();</code>定义一个变量<code>p</code>，则这个<code>p</code>只能调用<code>Object</code>类的方法，而不能调用<code>Person</code>类的方法。</p>
<h3 id="引用变量的强制类型转换"><a href="#引用变量的强制类型转换" class="headerlink" title="引用变量的强制类型转换"></a>引用变量的强制类型转换</h3><p>由于uubl只能调用编译时类型的方法，而不能调用运行时类型，即使它实际所引用的对象确实包含该方法。如果需要让这个引用变量调用它运行时类型的方法，则必须把它强制转为运行时类型。类型转换符用法是：<code>(type)variable</code>，这种用法可以将<code>variable</code>变量转成一个<code>type</code>类型的变量。除此之外，还可以将一个引用类型变量转成其子类类型。当进行强制类型转换时需要注意：</p>
<ul>
<li>基本类型的转换只能在数值类型之间进行，包括整数型、字符型和浮点型。但是数值类型和布尔类型之间不能进行类型转换。</li>
<li>引用类型之间的转换只能在具有继承关系的两个类型之间进行。如果实体把一个父类实例转换成子类类型，则这个对象必须实际上是子类类型（即编译时类型为父类类型，运行时类型是子类类型）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConversionTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> d = <span class="number">13.4</span>;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>) d;</span><br><span class="line">        System.out.println(l);</span><br><span class="line">        <span class="keyword">int</span> in = <span class="number">5</span>;</span><br><span class="line">        <span class="comment">//试图把一个数值类型的变量转换为boolean，下面代码会出错</span></span><br><span class="line">        <span class="comment">// boolean b = (boolean)in;</span></span><br><span class="line">        Object obj = <span class="string">"Hello"</span>;</span><br><span class="line">        <span class="comment">//obj变量的编译时类型是Object，Object和String之间有继承关系，可以强制转换</span></span><br><span class="line">        <span class="comment">//而且obj的实际类型是String，所以可以通过编译</span></span><br><span class="line">        String objstr = (String)obj;</span><br><span class="line">        System.out.println(objstr);</span><br><span class="line">        <span class="comment">//定义一个objPri变量，编译时类型为Object，实际类型为Integer</span></span><br><span class="line">        Object objPri = Integer.valueOf(<span class="number">5</span>);</span><br><span class="line">        <span class="comment">//objPri编译时类型为Object，运行时类型为Integer，所以以下代码会引发ClassCastExctption异常</span></span><br><span class="line">        String str = (String)objPri;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/04/20/%E9%85%92%E5%BA%97%E5%89%8D%E5%8F%B0%E5%AE%A2%E6%88%BF%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F2/" rel="prev" title="酒店前台客房管理系统2">
      <i class="fa fa-chevron-left"></i> 酒店前台客房管理系统2
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day9/" rel="next" title="Java日拱一卒-day9">
      Java日拱一卒-day9 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#final修饰符"><span class="nav-number">1.</span> <span class="nav-text">final修饰符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#final成员变量"><span class="nav-number">1.1.</span> <span class="nav-text">final成员变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#final局部变量"><span class="nav-number">1.2.</span> <span class="nav-text">final局部变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#final方法"><span class="nav-number">1.3.</span> <span class="nav-text">final方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#final类"><span class="nav-number">1.4.</span> <span class="nav-text">final类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多态"><span class="nav-number">2.</span> <span class="nav-text">多态</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#多态性"><span class="nav-number">2.1.</span> <span class="nav-text">多态性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引用变量的强制类型转换"><span class="nav-number">2.2.</span> <span class="nav-text">引用变量的强制类型转换</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="文予"
      src="/uploads/wenyu.png">
  <p class="site-author-name" itemprop="name">文予</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文予</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>


        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
